<template>
  <div class="article-page">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体内容 -->
    <el-card shadow="never" border="false">
      <!-- 头部 -->
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button icon="el-icon-plus" size="small" type="primary" round @click="openDrawer('add')">
            添加面经
          </el-button>
        </div>
      </template>
      <!-- 表格 -->
      <el-table stripe :data="articleList" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="365">
        </el-table-column>
        <el-table-column align="center" prop="creator" label="作者">
        </el-table-column>
        <el-table-column align="center" prop="likeCount" label="点赞">
        </el-table-column>
        <el-table-column align="center" prop="views" label="浏览数">
        </el-table-column>
        <el-table-column align="center" prop="createdAt" label="更新时间">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <div class="actions">
              <i class="el-icon-view" @click="openDrawer('preview', row.id)"></i>
              <i class="el-icon-edit-outline" @click="openDrawer('edit', row.id)"></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination :current-page="current" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 抽屉 -->
    <el-drawer :title="drawerTitle" :visible.sync="isShowDrawer" direction="rtl" :before-close="closeDrawer" size="60%">
      <!-- 预览 -->
      <div v-if="drawerType === 'preview'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
      <!-- 添加和编辑 -->
      <el-form v-else :model="form" :rules="rules" ref="drawerFormRef" label-width="80px">
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" type="text" placeholder="输入面经标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor v-model="form.content" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认</el-button>
          <el-button type="danger" @click="onClear">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getArticleListApi, createArticleApi, removeArticleApi, getArticleDetailApi, updateArticleApi } from '@/api/article'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      articleList: [],
      current: 1, // 当前页
      pageSize: 10, // 每页数据条数
      total: 0, // 总条数
      isShowDrawer: false, // 控制抽屉的显示/隐藏
      drawerType: '', // 打开抽屉要做什么
      form: {
        stem: '', // 标题
        content: '' // 内容
      },
      editorOption: {
        // 配置项，例如工具栏
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], // 字体
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image', 'video'] // 上传图片、上传视频
          ]
        }
      },
      rules: {
        stem: [
          { required: true, message: '请输入标题', blur: ['focus', 'change'] }
        ]
      }
    }
  },
  computed: {
    drawerTitle () {
      let title = '大标题'
      if (this.drawerType === 'edit') title = '修改面经'
      if (this.drawerType === 'add') title = '添加面经'
      if (this.drawerType === 'preview') title = '面经预览'
      return title
    }
  },
  created () {
    this.getArticleList()
  },
  methods: {
    // 1. 获取文章列表
    async getArticleList () {
      try {
        const res = await getArticleListApi({
          current: this.current,
          pageSize: this.pageSize
        })
        this.articleList = res.data.rows
        this.total = res.data.total
      } catch (error) {

      }
    },
    // 2. 删除
    async del (id) {
      try {
        await removeArticleApi(id)
        this.$message.success('删除成功')
        // 当前页是否还有最后一条数据
        // 数组长度为1 && 当前页不是第一页
        if (this.articleList.length === 1 && this.current > 1) {
          this.current -= 1
        }
        this.getArticleList()
      } catch (error) {

      }
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getArticleList()
    },
    handleCurrentChange (current) {
      this.current = current
      this.getArticleList()
    },
    // 3. 打开抽屉
    async openDrawer (type, id) {
      console.log(type, id)
      this.drawerType = type
      // 3.0 如果是编辑或者查看, 则根据id获取数据回显
      if (type !== 'add') {
        const res = await getArticleDetailApi(id)
        console.log(res)
        this.form = res.data
      }
      // 3.1 打开抽屉
      this.isShowDrawer = true
    },
    // 4. 关闭抽屉
    closeDrawer () {
      this.isShowDrawer = false
      this.onClear()
    },
    // 5. 富文本失焦
    onValidateQuill () {
      this.$refs.drawerFormRef.validateField(['content'])
    },
    // 6 .确认
    async onSubmit () {
      // 6.1 整体校验
      try {
        await this.$refs.drawerFormRef.validate()
        if (!this.form.content.trim()) {
          this.$message.error('请输入面经内容')
          return
        }
        // 6.2 调用接口
        if (this.drawerType === 'add') {
          await createArticleApi(this.form)
          this.$message.success('添加面经成功')
        } else if (this.drawerType === 'edit') {
          const { id, stem, content } = this.form
          await updateArticleApi({ id, stem, content })
          this.$message.success('更新面经成功')
        }

        // 6.4 关闭抽屉
        this.isShowDrawer = false
        // 6.5 重新加载
        this.current = 1
        this.getArticleList()
        // 6.6 清空输入框
        this.onClear()
      } catch (error) {

      }
    },
    // 7. 清空
    onClear () {
      if (this.drawerType !== 'preview') {
        this.$refs.drawerFormRef.resetFields()
      }

      this.form = {
        stem: '',
        content: ''
      }
      this.isShowDrawer = false // 关闭抽屉
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }

  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;

    >i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-breadcrumb {
  margin-top: 10px;
}

.el-form {
  padding-right: 40px;
}

.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}

.el-rate {
  padding: 10px 0;
}

.article-preview {
  padding: 0 40px 40px 40px;

  >h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
